package com.bsdsma.fengheguaiapp.restcontroller;

import com.bsdsma.fengheguaiapp.entity.ai.OpenAi;
import com.bsdsma.fengheguaiapp.service.impl.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("/api/v1/chat")
@CrossOrigin(
        origins = {"http://localhost:3000", "http://127.0.0.1:3000"},
        allowCredentials = "true",
        allowedHeaders = "*",
        methods = {RequestMethod.GET, RequestMethod.POST}
)
@Validated
@Slf4j
public class ChatController {
    private final OpenAiService openAiService;

    public ChatController(OpenAiService openAiService) {
        this.openAiService = openAiService;
    }

    @GetMapping(value = "/request", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> handleGetRequest(
            HttpServletResponse response,
            @RequestParam @NotBlank(message = "Question cannot be empty") String question) {
        log.info("Received chat request with question: {}", question);

        // 设置 SSE 必要的响应头
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        response.setHeader("X-Accel-Buffering", "no"); // 禁用 Nginx 缓冲

        return openAiService.submitQuestion(question)
                .doOnNext(msg -> log.debug("Sending message: {}", msg))
                .concatWith(Mono.just("[DONE]"))  // 在流结束时添加 [DONE] 标记
                .doOnComplete(() -> log.info("Chat request completed for question: {}", question))
                .doOnError(error -> log.error("Error processing chat request: {}", error.getMessage()));
    }

    @PostMapping(value = "/request",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> handlePostRequest(
            HttpServletResponse response,
            @RequestBody @Valid OpenAi openAi) {
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8");
        return openAiService.submitQuestion(openAi.getPrompt());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleValidationExceptions(ConstraintViolationException ex) {
        return ResponseEntity.badRequest().body(ex.getMessage());
    }
    /*private final OpenAiService openAiService;

    public ChatController(OpenAiService openAiService) {
        this.openAiService = openAiService;
    }

    @GetMapping(value = "/request", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> handleGetRequest(
            HttpServletResponse response,
            @RequestParam @NotBlank(message = "Question cannot be empty") String question,
            HttpServletRequest request) {
        log.info("Received GET request from: {}", request.getHeader("Origin"));
        log.info("Question: {}", question);

        // 设置SSE必要的响应头
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");
        response.setHeader("X-Accel-Buffering", "no"); // 禁用 Nginx 缓冲

        return openAiService.submitQuestion(question)
                .doOnNext(msg -> log.debug("Sending message: {}", msg))
                .doOnError(error -> log.error("Error in chat request", error))
                .doOnComplete(() -> log.info("Chat request completed"));
    }*/
}